package cn.bdqn.service.impl;

import cn.bdqn.mapper.ItemKillMapper;
import cn.bdqn.mapper.ItemKillSuccessMapper;
import cn.bdqn.pojo.ItemKill;
import cn.bdqn.pojo.ItemKillSuccess;
import cn.bdqn.service.ItemKillService;
import cn.bdqn.utils.SnowFlake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ItemKillServiceImpl implements ItemKillService {

    private static final Logger log = LoggerFactory.getLogger(ItemKillServiceImpl.class);

    @Resource
    private ItemKillMapper itemKillMapper;
    @Resource
    private ItemKillSuccessMapper itemKillSuccessMapper;

    @Override
    public List<ItemKill> findAllItemKill() {
        List<ItemKill> itemKills = itemKillMapper.findAllItemKill();
        return itemKills;
    }

    @Override
    public ItemKill findByItemId(Integer itemId) {
        ItemKill itemKill = itemKillMapper.findByItemId(itemId);
        if(itemKill != null){
            return itemKill;
        }else{
            throw new RuntimeException("该商品ID不存在");
        }
    }

    @Override
    public int updateById(Integer id) {
        //先验证库存是否充足
        ItemKill itemKill = itemKillMapper.selectById(id);
        if(itemKill.getTotal() > 0){
            //库存扣减
            int row = itemKillMapper.updateById(id);
            //验证库存扣减是否成功
            if(row > 0){
                //生成秒杀成功的订单
                row = createKillOrder();
            }
        }
        return 0;
    }

    /**
     * 创建秒杀订单
     */
    private int createKillOrder(){
        ItemKillSuccess itemKillSuccess = new ItemKillSuccess();
        SnowFlake snowFlake = new SnowFlake(1,1,1);
        itemKillSuccess.setCode(String.valueOf(snowFlake.nextId()));
        //itemKillSuccessMapper.insert();
        return 1;
    }
}
